//
//  ViewController.m
//  Server
//
//  Created by jyh on 2018/7/24.
//  Copyright © 2018年 huig. All rights reserved.
//

#import "ViewController.h"
#import "SocketManager.h"
#import "Immessage.pbobjc.h"
#import "MessageCompile.h"
@interface ViewController()<SocketManagerDelegate>

/** 要监听的端口号 */
@property (weak) IBOutlet NSTextField *postNum;

/** 要发送的信息 */
@property (weak) IBOutlet NSTextField *sendMessage;

/** 显示信息View */
@property (unsafe_unretained) IBOutlet NSTextView *showMessage;

/** 服务器管理者 */
@property (nonatomic, strong) SocketManager *socketManager;

@end

@implementation ViewController

- (SocketManager *)socketManager{
    if (!_socketManager) {
        _socketManager = [SocketManager shareInstance];
        _socketManager.delegate = self;
    }
    return _socketManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}


/** 开启服务器 */
- (IBAction)startNotice:(NSButton *)sender {
    BOOL isSuccess = [self.socketManager startConnectWithPost:self.postNum.intValue];
    if (isSuccess) {
        [self showMessageView:@"开启监听"];
        sender.enabled = NO;
    } else {
        [self showMessageView:@"开启监听失败!"];
    }
}

/** 发送系统信息 */
- (IBAction)sendMessageClick:(NSButton *)sender {
    NSString *message = [NSString stringWithFormat:@"系统群发:%@",self.sendMessage.stringValue];
    NSData *data = [MessageCompile packageMessage:message messageType:(messageTypeSystem) packageType:(packageTypeString)];
    [self.socketManager sendMessageToClient:data];
    [self showMessageView:message];
    self.sendMessage.stringValue = @"";
}

/** 显示信息 */
- (void)showMessageView:(NSString *)message {
    self.showMessage.string = [self.showMessage.string stringByAppendingFormat:@"%@\n",message];
    [self.showMessage scrollRangeToVisible:NSMakeRange(self.showMessage.string.length, 1)];
}

#pragma mark - 服务器SocketManagerDelegate
/** 接受到要显示的信息 */
- (void)socketManager:(SocketManager *)socket message:(NSString *)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showMessageView:message];
    });
}

@end




























